"use strict";
(function () {
    const Config = {
        maxTryNum: 3, // 最多尝试次数
        tryTime: 200, // 尝试间隔
        scrollAutoTopUp: true, // 推荐刷新后弹窗窗口自动置顶
        scrollSmooth: true, // 自动置顶平滑
        maxRecordNum: 3, // 最多保存轮次
        maxRecordSize: 30 // 每轮推荐最多保存数量
    };
    function main() {
        let gui = new GUI();
        let record = new Record();
        let PageHandler;
        if (!is_Bewly()) {
            // BiliBili
            PageHandler = new PageHandlerBili(jsSelector.Bili, gui, record);
        }
        else {
            // BewlyBewly
            PageHandler = new PageHandlerBewly(jsSelector.Bewly, gui, record);
        }
        PageHandler.start();
    }
    const jsSelector = {
        Bili: {
            getButtonElement: function () {
                return document.querySelector("#i_cecream > div.bili-feed4 > main > div.feed2 > div > div.feed-roll-btn > button");
            },
            getBoxElement: function () {
                return document.querySelectorAll("#i_cecream > div.bili-feed4 > main > div.feed2 > div > div.container.is-version8 > div");
            }
        },
        Bewly: {
            getButtonElement: function () {
                var _a, _b, _c;
                return (_c = (_b = (_a = document.querySelector("#bewly")) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector("#bewly-wrapper > div:nth-child(2) > aside > div > div.dock-content-inner > span:nth-child(1) > button")) !== null && _c !== void 0 ? _c : null;
            },
            getLinkElement: function () {
                var _a, _b, _c;
                return (_c = (_b = (_a = document.querySelector("#bewly")) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelectorAll("#bewly-wrapper > div:nth-child(4) > div > div:nth-child(2) > main > div > div > main > div > div.grid-adaptive > div > div > div > a")) !== null && _c !== void 0 ? _c : [];
            },
            getImgElement: function () {
                var _a, _b, _c;
                return (_c = (_b = (_a = document.querySelector("#bewly")) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelectorAll("#bewly-wrapper > div:nth-child(4) > div > div:nth-child(2) > main > div > div > main > div > div.grid-adaptive > div > div > div > a > div.group\\/cover.vertical-card-cover > picture > img")) !== null && _c !== void 0 ? _c : [];
            },
            getTextElement: function () {
                var _a, _b, _c;
                return (_c = (_b = (_a = document.querySelector("#bewly")) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelectorAll("#bewly-wrapper > div:nth-child(4) > div > div:nth-child(2) > main > div > div > main > div > div.grid-adaptive > div > div > div > a > div:nth-child(2) > div.group\\/desc > div:nth-child(1) > h3 > a")) !== null && _c !== void 0 ? _c : [];
            }
        }
    };
    function is_Bewly() {
        return (document.documentElement.className.indexOf('bewly') > -1);
    }
    class VideoData {
        constructor(link, img, text, single = false, tabBox = null) {
            this.link = link;
            this.img = img;
            this.text = text;
            this.single = single;
            this.tabBox = tabBox;
        }
    }
    class PageHandlerBase {
        constructor(selector, gui, record) {
            this.gui = gui;
            this.record = record;
            this.selector = selector;
            this.tryNum = 0;
        }
        start() { this.find(); }
        find() {
            let targetButton = this.selector.getButtonElement();
            if (targetButton) {
                targetButton.addEventListener('click', () => this.bindHandler(), true);
                this.bindInit();
            }
            else {
                this.tryNum += 1;
                if (this.tryNum < Config.maxTryNum) {
                    setTimeout(() => this.find(), Config.tryTime);
                }
                else {
                    console.warn('bilibili历史推荐记录，注入失败');
                }
            }
        }
        bindInit() { this.gui.insert(); }
        bindHandler() { }
    }
    class PageHandlerBili extends PageHandlerBase {
        constructor(selector, gui, record) { super(selector, gui, record); }
        bindInit() {
            super.bindInit();
            console.log('Find! BiliBili');
        }
        bindHandler() {
            let videoDataArray = new Array();
            let boxElementArray = this.selector.getBoxElement();
            if (boxElementArray.length == 1) {
                console.log('box get Error');
                return;
            }
            let forNum = 0;
            for (let i = 0; i < boxElementArray.length; i++) {
                if (forNum >= Config.maxRecordSize) {
                    break;
                }
                let boxElement = boxElementArray[i];
                let single = false;
                let tabBox = null;
                if (boxElement.className.indexOf('floor-single-card') > -1)
                    single = true;
                let linkElement = boxElement.querySelector('a');
                let imgElement = boxElement.querySelector('img');
                let textElement;
                if (!single) {
                    textElement = boxElement.querySelector('div.bili-video-card__info a');
                }
                else {
                    textElement = boxElement.querySelector('a > span');
                }
                let link = (linkElement && linkElement.href) || "";
                let img = (imgElement && imgElement.src) || "";
                let text = (textElement && textElement.innerHTML) || "";
                if (!link)
                    continue;
                if (single) {
                    tabBox = boxElement.querySelector('div.badge');
                }
                videoDataArray.push(new VideoData(link, img, text, single, tabBox));
                forNum += 1;
            }
            if (videoDataArray.length > 0) {
                this.record.push(videoDataArray);
            }
            this.gui.update(this.record.getRecordAll());
        }
    }
    class PageHandlerBewly extends PageHandlerBase {
        constructor(selector, gui, record) { super(selector, gui, record); }
        bindInit() {
            super.bindInit();
            console.log('Find! BewlyBewly');
        }
        bindHandler() {
            let videoDataArray = new Array();
            let linkElementArray = this.selector.getLinkElement();
            let imgElementArray = this.selector.getImgElement();
            let textElementArray = this.selector.getTextElement();
            if (!this.ElementArrayAssert(linkElementArray, imgElementArray, textElementArray)) {
                console.warn('Bewly get data Error');
                return;
            }
            let forNum = 0;
            for (let i = 0; i < linkElementArray.length; i++) {
                if (forNum >= Config.maxRecordSize) {
                    break;
                }
                let linkElement = linkElementArray[i];
                let imgElement = imgElementArray[i];
                let textElement = textElementArray[i];
                let link = (linkElement && linkElement.href) || "";
                let img = (imgElement && imgElement.src) || "";
                let text = (textElement && textElement.innerHTML) || "";
                if (!link)
                    continue;
                videoDataArray.push(new VideoData(link, img, text));
                forNum += 1;
            }
            if (videoDataArray.length > 0) {
                this.record.push(videoDataArray);
            }
            this.gui.update(this.record.getRecordAll());
        }
        ElementArrayAssert(arr1, arr2, arr3) {
            const length = arr1.length;
            return length === arr2.length &&
                length === arr3.length &&
                length > 0;
        }
    }
    class Record {
        constructor(maxRecordNum = 3) {
            this.recordAll = new Array();
            this.maxRecordNum = maxRecordNum;
        }
        push(videoDataArray) {
            this.recordAll.push(videoDataArray);
            if (this.recordAll.length > this.maxRecordNum) {
                this.recordAll.shift();
            }
        }
        getRecordAll() { return this.recordAll; }
    }
    class GUI {
        constructor() {
            this.refreshed = false;
            this.popupMain = null;
        }
        insert() {
            // 注入 HTML
            document.body.insertAdjacentHTML('beforeend', template.htmlButton);
            document.body.insertAdjacentHTML('beforeend', template.htmlPopup);
            // 注入样式
            GM_addStyle(template.style);
            this.buttonBind();
        }
        update(recordAll) {
            var _a, _b;
            this.clear();
            for (let i = 0; i < recordAll.length; i++) {
                let videoDataArray = recordAll[recordAll.length - 1 - i];
                let listBox = this.createListBox(videoDataArray, i);
                if (i > 0) {
                    (_a = this.popupMain) === null || _a === void 0 ? void 0 : _a.insertAdjacentHTML('beforeend', template.htmlHr);
                }
                (_b = this.popupMain) === null || _b === void 0 ? void 0 : _b.appendChild(listBox);
            }
            this.refreshed = true;
        }
        clear() { var _a; (_a = this.popupMain) === null || _a === void 0 ? void 0 : _a.replaceChildren(); }
        scrollTopUp() {
            if (!this.popupMain)
                return;
            if (Config.scrollSmooth) {
                if (!this.scrollSmoothTopUP())
                    window.requestAnimationFrame(() => this.scrollTopUp());
            }
            else {
                this.popupMain.scrollTop = 0;
            }
        }
        scrollSmoothTopUP() {
            if (!this.popupMain)
                return true;
            if (this.popupMain.scrollTop < 10) {
                this.popupMain.scrollTop = 0;
                return true;
            }
            else {
                let sTop = this.popupMain.scrollTop;
                this.popupMain.scrollTo(0, sTop - sTop / 16);
                return false;
            }
        }
        createListBox(videoDataArray, index) {
            let box = document.createElement('div');
            for (let i = 0; i < videoDataArray.length; i++) {
                let videoData = videoDataArray[i];
                let videoBox = this.createVideoBox(videoData, i);
                box.appendChild(videoBox);
            }
            return box;
        }
        createVideoBox(videoData, index) {
            let box = document.createElement('div');
            box.className = "video-box";
            box.innerHTML = `
            <a href="${videoData.link}">
                <img src="${videoData.img}"></img>
            </a>
            <div class="video-box-info">
                <a href="${videoData.link}"><h2>&emsp;${videoData.text}</h2></a>
                <div class="video-box-tab">
                    ${this.createVideoTab(videoData, index)}
                </div>
            </div>
            `;
            return box;
        }
        createVideoTab(videoData, index) {
            var _a;
            let div = "";
            if (videoData.single) {
                div += `<div class="tab-badge">${(_a = videoData.tabBox) === null || _a === void 0 ? void 0 : _a.innerHTML}</div>`;
            }
            div += `
                <div class="tab-index">
                    <div class="tab-index-pedestal">
                        <h1>${index + 1}</h1>
                    </div>
                </div>
                `;
            return div;
        }
        buttonBind() {
            // 获取元素
            const btn = document.querySelector('#myCustomButton');
            const popup = document.querySelector('#myPopup');
            const closeBtn = document.getElementById('closePopup');
            this.popupMain = document.getElementById('popup-main');
            // 按钮点击事件
            btn === null || btn === void 0 ? void 0 : btn.addEventListener('click', () => {
                if (popup) {
                    popup.style.display = 'flex';
                }
                ;
                if (Config.scrollAutoTopUp && this.refreshed) {
                    this.scrollTopUp();
                }
                this.refreshed = false;
            });
            // 关闭按钮事件
            closeBtn === null || closeBtn === void 0 ? void 0 : closeBtn.addEventListener('click', () => {
                popup.style.display = 'none';
            });
            // 点击外部关闭弹窗
            window.addEventListener('click', (e) => {
                var _a;
                const target = e.target;
                if ((_a = target.classList) === null || _a === void 0 ? void 0 : _a.contains('popup-overlay')) {
                    popup.style.display = 'none';
                }
            });
        }
    }
    const template = {
        // <hr>模板
        htmlHr: `<hr align="center" width="100%" color="#987cb9" style="height: 5px;">`,
        // Button按钮模板
        htmlButton: `<button id="myCustomButton" class="custom-btn">历史</button>`,
        // Popup弹窗模板
        htmlPopup: `
            <div id="myPopup" class="popup-overlay">
                <div class="popup-content">
                    <span class="close-btn" id="closePopup">&times;</span>
                    <h2>推荐历史记录</h2>
                    <hr>
                    <div id="popup-main">
                        <p>暂无推荐纪录，请刷新推荐。</p>
                    </div>
                </div>
            </div>`,
        // CSS样式模板
        style: `
            #popup-main {
                overflow: auto;
                margin: 20px 10px 0 10px;
                max-height: 75vh;
            }
            
            .video-box {
                display: flex;
                background-color: rgb(255, 240, 240);
                margin: 10px 0;
                padding: 10px 5px;
                border-radius: 15px;
            }
            
            .video-box img {
                max-width: 480px;
                border-radius: 12px;
                min-width: 480px;
                min-height: 270px;
            }

            .video-box-info {
                display: flex;
                padding: 0 10px;
                width: 100%;
                flex-direction: column;
            }
            
            .video-box-tab {
                flex: 1;
                display: flex;
                align-items: flex-end;
            }
            
            .tab-index {
                flex: 1;
                text-align: right;
                display: flex;
                justify-content: flex-end;
            }

            .tab-index-pedestal {
                    display: flex;
                    height: 50px;
                    width: 50px;
                    border-radius: 25px;
                    background: var(--success_green);
                    box-shadow: 5px  5px 8px #989898,
                               -5px -5px 8px #ffffff;
                    justify-content: center;
                    align-items: center;
            }
            
            .tab-index :is(h1, h2, h3, h4, h5, h6) {
                color: white;
            }
            
            .tab-badge {
                text-align: left;
                height: 27px;
                background: white;
                padding: 0 6px;
                display: flex;
                align-items: center;
                border-radius: 6px;
            }

            /* 按钮样式 */
            .custom-btn {
                position: fixed;
                left: 20px;
                top: 35%;
                transform: translateY(-50%);
                width: 50px;
                height: 50px;
                border-radius: 50%;
                background: #ff0000 !important;
                color: white;
                border: none;
                cursor: pointer;
                font-size: 14px;
                line-height: 50px;
                text-align: center;
                padding: 0;
                z-index: 9998;
                box-shadow: 0 2px 5px rgba(0,0,0,0.3);
            }

            /* 弹窗遮罩层 */
            .popup-overlay {
                display: none;
                justify-content: center;

                align-items: flex-start;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 9999;
            }

            /* 弹窗内容 */
            .popup-content {
                position: relative;
                background: white;
                max-width: 50%;
                margin: 70px auto;
                padding: 20px;
                border-radius: 8px;
                animation: slideIn 0.3s;
                min-width: 25%;
            }

            /* 关闭按钮 */
            .close-btn {
                position: absolute;
                top: 10px;
                right: 15px;
                font-size: 24px;
                cursor: pointer;
            }

            /* 动画效果 */
            @keyframes slideIn {
                from { transform: translateY(-50px); opacity: 0; }
                to { transform: translateY(0); opacity: 1; }
            }`
    };
    // 执行主函数
    main();
})();
